<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    ul {
      list-style: none;
    }

    h1 {
      text-align: center;
      margin: 20px;
    }

    h2 {
      text-align: center;
    }

    .voteBox {
      display: flex;
      justify-content: center;
      padding: 20px;
    }

    .vote {
      min-width: 500px;
      width: 500px;
      height: 400px;
      border: 2px solid #ccc;
      overflow: auto;
      border-radius: 10px;
      margin-right: 20px;
    }

    #main {
      min-width: 700px;
      width: 400px;
      height: 400px;
      border: #ccc 1px solid;
      margin-left: 20px;
    }

    .vote li {
      height: 40px;
      display: flex;
      justify-content: space-between;
      padding: 0px 20px;
      border: 1px solid #ccc;
      margin: 10px;
      align-items: center;
      border-radius: 20px;
      line-height: 0;
    }

    .vote li p {
      width: 230px;
      line-height: 16px;
      font-size: 16px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .vote li span {
      color: orangered;
      font-size: 12px;
    }

    .vote li button {
      background-color: #000;
      color: white;
      padding: 8px;
      font-size: 12px;
      border-radius: 10px;
      cursor: pointer;
      line-height: 1;
      border: none;
    }

    .vote li button:hover {
      color: white;
    }

    .createBox {
      padding: 0px 20px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      width: 250px;
      align-items: center;
    }

    .addInp {
      width: 200px;
      height: 20px;
      outline: none;
      text-indent: 10px;
      border-radius: 20px;
      border: 2px solid #333;
    }
  </style>
</head>

<body>
  <h1>投票系统</h1>
  <div class="voteBox">
    <div class="vote">
      <ul class="voteList">
      </ul>
    </div>
    <div id="main"></div>
  </div>
  <div class="createBox">
    <input class="inp" type="text" placeholder="创建投票" name="" id="">
    <button class="create">创建投票</button>
  </div>
  <script src="/socket.io/socket.io.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <script type="module">

    // 创建echars图表
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));

    // 指定图表的配置项和数据
    let option = {
      emphasis: {
        label: {
          show: true,
          fontWeight: 'bold',
          color: "red"
        }
      },
      series: [
        {
          type: 'pie',
          radius: "130",
          stillShowZeroSum: false,
          data: [],
          label: {
            formatter: '{b}: {d}%' // {b}代表name属性，{c}代表value属性，{d}%代表百分比
          }
        }
      ]
    }

    const socket = io()
    import axios from "./axios.js"
    // 获取dom
    const voteList = document.querySelector(".voteList")
    const chooseName = document.querySelector(".chooseName")
    const chooseNum = document.querySelector(".chooseNum")
    const choosed = document.querySelector(".choosed")
    const create = document.querySelector(".create")

    // 用户名
    let user = localStorage.getItem("user")

    // 获取投票
    getVote()

    // 投票事件委托
    voteList.onclick = function (e) {
      if (e.target.nodeName === "BUTTON" && e.target.className !== "addBtn") {
        void voted(e.target.dataset.id, e)
      }
      if (e.target.className === "addBtn") {
        const value = e.target.previousElementSibling.value
        void addVote(value)
      }
    }

    // 后端投票监听事件
    socket.on("vote", id => {
      getVote()
    })

    // 创建投票按钮
    create.onclick = function () {
      const inp = document.querySelector(".inp").value
      if (inp.length == 0) return alert("请输入投票选项")
      const options = inp.split(",")
      createVote(options)
    }

    // 投票 参数,投票的id
    async function voted(id, e) {
      const appVersion = navigator.appVersion
      const userAgent = navigator.userAgent
      // 投票之前判断是否登录
      if (!user) {
        var r = prompt("投票前请先登录(用户名只能是2-5位)")
        if (r === null) return
        if (!/^.{2,5}$/.test(r)) {
          return alert("用户名只能是2-5位")
        }
        user = r
        localStorage.setItem("user", user)
        return
      }
      /* 
        浏览器平台和版本信息: navigator.appVersion
        客户机发送服务器的user-agent头部的值: navigator.userAgent
        投票选择的id
      */

      const choose = e.target.previousElementSibling.previousElementSibling.innerHTML

      if (!confirm(`您确认投给${choose}`)) return
      const { data: res } = await axios.post("/vote", {
        appVersion,
        userAgent,
        username: user,
        id
      })
      if (res.code == 1) {
        socket.emit("vote")
        alert(res.message)
      } else {
        alert(res.message)
      }
    }

    // 创建投票
    async function createVote(options) {
      const password = prompt("请输入创建密码")
      const { data: res } = await axios.post("/create", {
        options,
        password
      })
      if (res.code == 1) {
        alert(res.message)
      } else {
        alert(res.message)
      }

      // 创建完成投票后,让所有客户端的代码重新渲染
      socket.emit("vote")
    }

    // 获取投票
    async function getVote() {
      const { data: res } = await axios.get("/getVote")
      console.log(res);
      if (res.code != 1) {
        return alert("获取投票失败")
      }

      if (res.data.length == 0) {
        voteList.innerHTML = "<li><h2>暂无投票</h2></li>"
        return
      }

      const obj = JSON.parse(res.data[0].options)
      console.log(obj);

      voteList.innerHTML = "<li><input class='addInp' type='text'><button class='addBtn'>新增投票</button></li>"

      option.series[0].data = []

      for (const i in obj) {
        // 设置横轴
        option.series[0].data.push({
          value: obj[i],
          name: i
        })
        voteList.innerHTML += `
        <li>
          <p class="chooseName">${i}</p>
          <span class="chooseNum">已投:${obj[i]}</span>
          <button class="choosed" data-id="${i}">投票</button>
        </li>
        `
      }

      console.log(option);
      // 修改echarts图
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)

    }

    // 增加投票
    async function addVote(value) {
      if(value.length == 0) return alert("请输入选项内容")
      if (!confirm(`是否增加选项${value}`)) return
      const { data: res } = await axios.post("/add", {
        option: value
      })
      if (res.code == 1) {
        alert(res.message)
      } else {
        alert(res.message)
      }

      // 创建完成投票后,让所有客户端的代码重新渲染
      socket.emit("vote")
    }
  </script>
</body>

</html>